local UIBase = require("view.UIBase")
local PopupMagickeyChoose = class("PopupMagickeyChoose", UIBase)

local MAX_ITEM = 5

function PopupMagickeyChoose:ctor(callback)
    self._callback = callback
    local resource = {
        path = "Prefabs/View/MagicKey",
        name = "PopupMagickeyChoose",
        canvas = 3
    }
    PopupMagickeyChoose.super.ctor(self, resource)
end

function PopupMagickeyChoose:start()
    self._selectedId = 0
    self._btnOk.onClick:AddListener(handler(self, self._onBtnokClick))
    self._btnClose.onClick:AddListener(handler(self, self._onBtnCloseClick))
    self._listView:SetTemplate(
        handler(self, self._onItemUpdate),
        handler(self, self._onValueChange),
        handler(self, self._onItemTouch)
    )
    self._dataList = G_UserData:getMagickey():getList()
    local count = math.ceil(#self._dataList / MAX_ITEM)
    self._listView:ReSize(count)
end

function PopupMagickeyChoose:_onItemUpdate(item, index)
    local startIndex = index * MAX_ITEM + 1
    local endIndex = startIndex + MAX_ITEM - 1
    local line = {}
    for i = startIndex, endIndex do
        local data = self._dataList[i]
        if data then
            table.insert(line, data)
        end
    end
    item:updateUI(line, self._selectedId)
end

function PopupMagickeyChoose:_onValueChange()
end

function PopupMagickeyChoose:_onItemTouch(id)
    self._selectedId = id
    self._listView:UpdateUsedCell()
end

function PopupMagickeyChoose:_onBtnokClick()
    if self._callback then
        self._callback(self._selectedId)
    end
    self:close()
end

function PopupMagickeyChoose:_onBtnCloseClick()
    self:close()
end

return PopupMagickeyChoose
